﻿using AutoMapper;
using B.S.BaseData.Domain.Entities.RBAC;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.ErrorCode.ErrorCodes;
using B.S.BaseData.Infrastructure.Implements;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.DataBase.EFCoreServiers.Dtos.Roles;
using B.S.DataBase.EFCoreServiers.IServices.Roles;
using Microsoft.EntityFrameworkCore;

namespace B.S.DataBase.EFCoreServiers.Services.Roles
{
    public class RoleServices : IRoleServices
    {
        private readonly IRoleRepository roleRepository;
        private readonly IMapper mapper;
        private readonly IDepartmentRepository deptRep;

        public RoleServices(IRoleRepository roleRepository,IMapper mapper, IDepartmentRepository deptRep)
        {
            this.roleRepository = roleRepository;
            this.mapper = mapper;
            this.deptRep = deptRep;
        }
       /// <summary>
       /// 角色新增
       /// </summary>
       /// <param name="RoleDto"></param>
       /// <returns></returns>
        public async Task<ApiResult> AddRoleAsync(AddRoleDto RoleDto)
        {
            try
            {
                var existingRole = await roleRepository.GetAll().FirstOrDefaultAsync(x => x.RoleName == RoleDto.RoleName);
                if(existingRole!= null)
                {
                    return ApiResult.Fail("角色名称已存在", StatusCodeEnum.Fail);
                }
                
                var list = mapper.Map<Role>(RoleDto);
                // 添加角色并保存更改
                // AddAsync方法内部已经包含了SaveChanges操作，不需要重复调用
                await roleRepository.AddAsync(list);

                return ApiResult.Success(StatusCodeEnum.Ok);
            }
            catch (Exception ex)
            {
                return ApiResult.Fail("添加角色失败：" + ex.Message, StatusCodeEnum.Exception);
            }
        }
        /// <summary>
        /// 删除角色信息
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult> DeleteRoleAsync(int roleId)
        {
           
            try
            {
                var list = await roleRepository.GetAll().FirstOrDefaultAsync(x => x.RoleId == roleId);
                if (list == null)
                {
                    return ApiResult.Fail("角色不存在", StatusCodeEnum.ObjNotFound);
                }
                // 删除角色
                await roleRepository.DeleteAsync(list);
                return ApiResult.Success(StatusCodeEnum.Ok);
            }
            catch (Exception ex)
            {
                return ApiResult.Fail("删除角色失败：" + ex.Message, StatusCodeEnum.Exception);
            }
        }

        /// <summary>
        /// 获取角色列表分页
        /// </summary>
        /// <param name="roleDto"></param>
        /// <returns></returns>
        public async Task<ApiResult<ApiPaging<GetRoleResponseDto>>> GetRoleListAsync(GetRoleDto roleDto)
        {
            try
            {
                // 获取角色列表分页
                var list = await roleRepository.GetPageListAsync(
                    roleDto.pageIndex,
                    roleDto.pageSize,
                    x => x.RoleName.Contains(roleDto.RoleName) || string.IsNullOrEmpty(roleDto.RoleName)
                );

                // 转换类型
                var dto = mapper.Map<IList<GetRoleResponseDto>>(list.Data);

                // 获取所有部门信息
                var deptList = await deptRep.GetAll().ToListAsync();

                // 通过DeptId为每个角色DTO赋值部门名称和成员数量
                foreach (var roleDtoItem in dto)
                {
                    // 找到当前角色对应的部门
                    var roleEntity = list.Data.FirstOrDefault(r => r.RoleId == roleDtoItem.RoleId);
                    var dept = deptList.FirstOrDefault(d => d.DeptId == roleEntity?.DeptId);

                    roleDtoItem.DepartmentName = dept?.DepartmentName ?? string.Empty;
                    roleDtoItem.MemberCount = dept?.MemberCount ?? 0;
                }

                ApiPaging<GetRoleResponseDto> pageDto = new ApiPaging<GetRoleResponseDto>(list.TotalCount, list.TotalPage, dto);
                return ApiResult<ApiPaging<GetRoleResponseDto>>.Success(pageDto, StatusCodeEnum.Ok);
            }
            catch (Exception ex)
            {
                return ApiResult<ApiPaging<GetRoleResponseDto>>.Fail("角色列表出错：" + ex.Message, StatusCodeEnum.Exception);
            }
        }
        /// <summary>
        /// 编辑角色信息
        /// </summary>
        /// <param name="roleName"></param>
        /// <param name="description"></param>
        /// <returns></returns>
        public async Task<ApiResult> UpdateRoleAsync(UpdateRoleDto roleDto)
        {
            try
            {
                // 判断是否有其他角色使用了相同的角色名称（排除当前角色）
                var exist = await roleRepository.GetAll()
                    .AnyAsync(x => x.RoleName == roleDto.RoleName && x.RoleId != roleDto.RoleId);

                if (exist)
                {
                    return ApiResult.Fail("角色名称已存在", StatusCodeEnum.Fail);
                }

                // 获取当前要编辑的角色
                var role = await roleRepository.GetAll().FirstOrDefaultAsync(x => x.RoleId == roleDto.RoleId);
                if (role == null)
                {
                    return ApiResult.Fail("角色不存在", StatusCodeEnum.ObjNotFound);
                }

                // 更新角色信息
                role.RoleName = roleDto.RoleName;
                role.Description = roleDto.Description;

                await roleRepository.UpdateAsync(role);

                return ApiResult.Success(StatusCodeEnum.Ok);
            }
            catch (Exception ex)
            {
                return ApiResult.Fail("编辑角色失败：" + ex.Message, StatusCodeEnum.Exception);
            }
        }
        /// <summary>
        /// 修改角色状态
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public async Task<ApiResult> UpdateStateRoleAsync(int roleId)
        {
            try
            {
                // 查到当前角色是否存在
                var info = await roleRepository.GetAll()
                    .FirstOrDefaultAsync(x => x.RoleId == roleId);

                if (info==null)
                {
                    return ApiResult.Fail("角色不存在", StatusCodeEnum.Fail);
                }

                if(info.IsEnabled==true)
                {
                    info.IsEnabled = false; // 如果当前状态是启用，则改为禁用
                }
                else
                {
                    info.IsEnabled = true; // 如果当前状态是禁用，则改为启用
                }


                await roleRepository.UpdateAsync(info);

                return ApiResult.Success(StatusCodeEnum.Ok);
            }
            catch (Exception ex)
            {
                return ApiResult.Fail("修改角色状态失败：" + ex.Message, StatusCodeEnum.Exception);
                ;
            }
        }



    }
}
